<?php
/**
 * 退款事件模型
 * @author Max.Yu <max@jipu.com>
 */

namespace Shop\Event;

class RefundEvent{

  /**
   * 执行退款
   * @param array $ids 订单编号集合
   * @param string $dotype 执行类型（cancel取消订单，refund退款）
   * @return array 执行结果
   */
  public function doit($ids,$oids, $dotype = 'cancel'){
    $return_data = array('code' => 300);
    $map['id'] = array('in', $ids);

    //状态修改 改成退款中
    if(M('StoreOrder')->where($map)->setField('o_status', ($dotype == 'cancel' ? 404 : 303))){
      //平台订单同步
      $where['id'] = array('in',$oids);
      M('Order')->where($where)->setField('o_status', ($dotype == 'cancel' ? 404 : 303));
      //处理库存和退款
      $order_lists = D('Order')->lists($where);
      //店铺ID
      $store_id = $order_lists[0]['store_ids'];
      //可退款金额
      $back_data = $this->getBackAmount($ids[0]);
      if($order_lists){
        foreach($order_lists as $key => $value){
          //商品库存处理
          $order_items = get_order_item($value['id']);
          if($order_items){
            $item_model = M('Item');
            foreach($order_items as $item){
              //判断商品是否存在规格 buddha 金海 20170807
              if ($item['item_code'] != $item['number']) {
                 M('ItemSpecifiction')->where(array('spc_code' => $item['item_code'],'item_id'=>$item['item_id']))->setInc('quantity', $item['quantity']);
              }
              $item_model->where('id='.$item['item_id'])->setInc('stock', $item['quantity']);
              //分销订单返现取消处理
              if($value['sdp_uid'] > 0 ){
                $this->sdp_refund($ids[0],$item['sdp_code'],$item['item_id']);
              }
            }
          }
          
          // 支付表记录
          $payment = M('Payment')->getById($value['payment_id']);

          // 积分退还处理
          $this->refundScore($ids[0],$value['order_sn'],$back_data);
          // 礼品卡返回处理
          if($payment['is_use_card'] > 0){
            $this->refundCard($value['order_sn'],$store_id,$back_data,$payment);
          }
          // 优惠券返回处理
          $back_coupon = unserialize($value['store_coupons']);
          if($back_coupon['store_coupon_use'][$store_id] == 1){
            $this->refundCoupon($value['id'],$store_id);
          }
          
          //第三方退款处理 也就是平台方进行退款
          if($payment['payment_amount'] > 0){
            //三方退款 订单状态修改 订单退款处理中 start buddha
            M('StoreOrder')->where($map)->setField('o_status', ($dotype == 'cancel' ? 404 : 304));
            $where['id'] = array('in',$oids);
            M('Order')->where($where)->setField('o_status', ($dotype == 'cancel' ? 404 : 303));
            //三方退款 订单状态修改 订单退款处理中 end buddha
            $payment_return = json_decode($payment['payment_return'], true);
            $trade_no = $payment_return['trade_no'];
            $trade_no = (!empty($trade_no)) ? $trade_no : ( (!empty($payment_return['transaction_id'])) ? $payment_return['transaction_id'] : $payment_data['payment_sn'] );
            $refund_data = array(
              'uid' => $value['uid'],
              'store_id'=>$value['store_ids'],
              'order_id' => $ids[0],
              'payment_type' => $payment['payment_type'],
              'trade_no' => $trade_no,
              'refund_type' => 'item',
              'amount' => $payment['payment_amount'],
              'detail' => '购物退款',
              'seller_status' =>2 ,
              'refund_status'=> 2,
            );
            D('Refund')->update($refund_data);
          }
          
          //账户余额返还
          if($payment['is_use_finance'] && $payment['finance_amount'] > 0){
            $this->refundFinance($value['id'],$value['finance_amount']);
          }
          
          //推广联盟取消
          $this->series_refund($ids[0]);

          //其他现金流水
          $this->other_refund($value['id'],$value['order_sn'],$store_id,$ids[0],$dotype); 
        }
      } 
      $return_data = array('code' => 200, 'info' => '订单'.($dotype == 'cancel' ? '取消' : '退款').'成功！');
    }else{
      $return_data = array('code' => 300, 'info' => '订单'.($dotype == 'cancel' ? '取消' : '退款').'失败！');
    }
    return $return_data;
  }

  /**
   * 自定义退款操作
   * @return [type] [description]
   */
  public function doitNew($ids, $oids, $dotype = 'cancel'){
    $return_data = array('code' => 300);
    $map['id'] = array('in', $ids);
    if(M('StoreOrder')->where($map)->setField('o_status', ($dotype == 'cancel' ? 404 : 303))){
      //处理库存和退款
      $where['id'] = array('in',$oids);
      $order_lists = D('Order')->lists($where);
      //商户订单表
      $store_order_list = D('StoreOrder')->lists($map);
      $item_ids = str2arr($store_order_list[0]['item_ids']);
      //可退款金额
      $back_data = $this->getBackAmount($ids[0]);
      set_log('refund-test',$back_data,'refund');
      //店铺ID
      $store_id = $store_order_list[0]['store_ids'];
      if($order_lists){
        foreach($order_lists as $key => $value){
          $order_items = get_order_item($value['id']);
          if($order_items){
            $item_model = M('Item');
            foreach($order_items as $item){
              //商品库存处理
              if (in_array($item['item_id'],$item_ids)) {
                //判断商品是否存在规格 buddha 金海 20170807
                if ($item['item_code'] != $item['number']) {
                   M('ItemSpecifiction')->where(array('spc_code' => $item['item_code'],'item_id'=>$item['item_id']))->setInc('quantity', $item['quantity']);
                }
                $item_model->where('id='.$item['item_id'])->setInc('stock', $item['quantity']);
                //分销订单返现取消处理
                if($value['sdp_uid'] > 0 ){
                  $this->sdp_refund($ids[0],$item['sdp_code'],$item['item_id']);
                }
              }
            }
          }
          //查询支付表
          $payment_data = M('Payment')->find($value['payment_id']);

          // 积分退还处理
          $this->refundScore($ids[0],$value['order_sn'],$back_data);
          
          // 礼品卡返回处理
          if($payment_data['is_use_card'] > 0){
            $this->refundCard($value['order_sn'],$store_id,$back_data,$payment_data);
          }
          // 优惠券返回处理
          $back_coupon = unserialize($value['store_coupons']);
          if($back_coupon['store_coupon_use'][$store_id] == 1){
            $this->refundCoupon($value['id'],$store_id);
          }

          // 第三方退款处理 也就是平台方进行退款 (三方支付了且可退款金额大于0)
          if( ($payment_data['payment_amount'] > 0 ) && ($back_data['back_use_online'] > 0 ) ){

            // 三方退款 订单状态修改 订单退款处理中
            M('StoreOrder')->where($map)->setField('o_status', ($dotype == 'cancel' ? 404 : 304));
            $payment_return = json_decode($payment_data['payment_return'], true);
            $trade_no = $payment_return['trade_no'];
            $trade_no = (!empty($trade_no)) ? $trade_no : ( (!empty($payment_return['transaction_id'])) ? $payment_return['transaction_id'] : $payment_data['payment_sn'] );
            $refund_data = array(
              'uid' => $value['uid'],
              'store_id'=>$store_id,
              'order_id' => $ids[0],
              'payment_type' => $payment_data['payment_type'],
              'trade_no' => $trade_no,
              'refund_type' => 'item',
              'amount' => $back_data['back_use_online'],
              'detail' => '购物退款',
              'seller_status' =>2 ,
              'refund_status'=> 2,
            );
            D('Refund')->update($refund_data);
          }
          
          // 账户余额返还处理
          if( $payment_data['is_use_finance'] &&  ($payment_data['finance_amount'] > 0) && $back_data['back_use_finance'] > 0){
              $this->refundFinance($value['id'],$back_data['back_use_finance']);
          }
          
          // 推广联盟取消处理
          $this->series_refund($ids[0]);

          //其他现金流水
          $this->other_refund($value['id'],$value['order_sn'],$store_id,$ids[0],$dotype);  

        }
      }    
      $return_data = array('code' => 200, 'info' => '订单'.($dotype == 'cancel' ? '取消' : '退款').'成功！');
    }else{
      $return_data = array('code' => 300, 'info' => '订单'.($dotype == 'cancel' ? '取消' : '退款').'失败！');
    }
    return $return_data;
  }

  /**
   * 退款成功后，更新退款订单
   */
  public function afterRefundSuccess($refund_no, $refund_info){
    //获取退款订单信息
    $refund_details = explode('#', $refund_info['details']);
    add_wechat_log($refund_details, 'refund-details');
    if($refund_details){
      foreach($refund_details as $key => $value){
        $refund_item = explode('^', $value);
        $refund_map = array(
          'trade_no' => $refund_item[0],
          'refund_no' => $refund_no
        );
        $refund_orders = M('Refund')->where($refund_map)->select();
        foreach($refund_orders as $refund_order){
          if(($refund_item[2] == 'SUCCESS') && ($refund_order['refund_status'] == 0)){
            $refund_data = array(
              'refund_status' => 3,
              'refund_return' => json_encode($refund_info)
            );
            add_wechat_log($refund_data, 'refund-data');
            M('Refund')->where('id = '.$refund_order['id'])->save($refund_data);
            if($refund_order['type'] == 1){
              $this->series_refund($refund_order['order_id']);
            }elseif($refund_order['type'] == 2){
              $this->handlejoin($refund_order['order_id']);
            }
          }
        }
      }
    }
  }

  /**
   * 处理团购订单退款
   * @param  [type] $order_id [description]
   * @return [type]           [description]
   */
  function handlejoin($order_id){
    if($result = M('Join_order')->alias('a')->join('RIGHT JOIN __JOIN_LIST__ b on a.join_id=b.id')->where('a.id='.$order_id.' and b.status=2')->getField('a.join_id')){
      M('Join_list')->where('id='.$result)->setField('status' ,3);
    }
  }

  /**
   * 推广联盟返现取消
   * @param  [type] $orderid [description]
   * @return [type]          [description]
   */
  function series_refund($order_id){
    $where['type']   = array('in' ,array('union_order')) ;
    $where['flow']   = 'in' ;
    $where['status'] = 0 ;
    $where['order_id']     = $order_id ;
    $result = M('Finance')->where($where)->getField('id' ,true);
    if(!$result){
      return false;
    }

    $map = arr2str($result);

    M('Finance')->where('id in ('.$map.')')->setField('status' , '2');
    $users = M('Finance')->where('id in ('.$map.')')->field('uid,amount')->select();
    foreach($users as $k => $v){
      M('Member')->where('uid ='.$v['uid'])->setDec('finance' ,$v['amount']);
    }
  }

  /**
   * 分销店铺返现取消
   * @author buddha <[email address]>
   * @param  [type] $order_id [description]
   * @return [type]           [description]
   */
  public function sdp_refund($order_id,$sdp_code,$item_id){
    $order_sn = M('StoreOrder')->where('id='.$order_id)->getField('order_sn');
    $res = M('shop')->where('secret="'.$sdp_code.'"')->find();
    $map = array(
        'order_id' => $order_id,
        'type'     => 'sdp_order',
        'flow'     => 'in'
      );
    $status = M('Finance')->where($map)->getField('status');
    $where = array(
        'sdp_uid'  => $res['uid'], 
        'order_id' => $order_id,
        'item_id'  => $item_id
      );
    $sdp_amount = M('SdpRecord')->where($where)->sum('cashback_amount');
    $log = M('SdpRecord')->where($where)->find();
    if ($log) {
      $finance_data = array(
                'uid' => $res['uid'],
                'order_id' => $order_id,
                'type' => 'sdp_refund',
                'amount' => $sdp_amount,
                'flow' => 'out',
                'memo' => '分销订单退款，订单号：'.$order_sn,
                'create_time' => NOW_TIME
        );
        if($status == 1){
            M('Finance')->add($finance_data);
        }else{
          if(M('Finance')->add($finance_data)){
            // 将原来分销订单返现 状态设置
            M('Finance')->where(array('order_id'=>$order_id,'type'=>'sdp_order','flow'=>'in'))->setField('status','1');
          }
        }
       //分销店铺累计收入扣除
       M('Shop')->where('uid='.$res['uid'])->setDec('total_revenue', $sdp_amount);
       //扣除用户账户可提现金额
       M('Member')->where('uid = '.$res['uid'])->setDec('finance', $sdp_amount); 
    }

  }

  /**
   * 商户流水记录
   * @author buddha <[email address]>
   * @param  [type] $order_id 商户订单ID
   * @param  [type] $order_id 商户订单号
   * @param  [type] $order_id 商户店铺ID
   * @param  [type] $old_order_id 平台店订单ID
   * @return [type] [description]
   */
  public function other_refund($order_id,$order_sn,$store_id,$new_order_id,$dotype){
      $cash_event = A('Home/StoreCash','Event');
      $order_event = A('Home/Order','Event');
      //订单支付后的资金流水 
      $cash_event->orderPaid($order_sn,2,$store_id);
      //推广联盟的商户流水
      if( C('DIS_ORDERSTATUS') == 1){
        $cash_event->distribute($order_id,2,$store_id);
      }
      //商户分销店铺流水
      $cash_event->sdpOrder($order_id,2,$store_id);
      //平台订单表同步
      $o_status = ($dotype == 'cancel' ? 404 : 303);
      $count = $order_event->checkOrderCount($new_order_id);
      $store_count = $order_event->checkOrderStatusCount(array('o_status'=>303),$order_sn);
      if ($count == 1 || ($count-1)==$store_count) {
        M('Order')->where(array('order_sn'=>$order_sn))->setField('o_status', $o_status);
      }
  }

  /**
   * 账户余额返还处理
   */
  public function refundFinance($order_id,$refund_fee){
    $memo = '订单退款';
    $order = M('Order')->find($order_id);
    if($order && $order['finance_amount'] > 0){
      //更新用户账户余额
      $update_member = M('Member')->where('uid = '.$order['uid'])->setInc('finance', $refund_fee);
      if($update_member){
        //增加更新记录
        $data_finance = array(
          'uid' => $order['uid'],
          'order_id' => $order['id'],
          'type' => 'refund',
          'amount' => $refund_fee,
          'flow' => 'in',
          'memo' => $memo,
          'create_time' => NOW_TIME
        );
        $update_finance = M('Finance')->add($data_finance);
      }
    }
  }

  /**
   * 优惠券返还处理
   */
  public function refundCoupon($order_id,$store_id){
    $res = M('CouponUser')->where(array('order_id'=>$order_id,'store_id'=>$store_id))->find();
    if ($res) {
      //优惠券使用记录
      $data = array(
          'status'=>0,
          'use_time'=>0,
          'use_amount'=>0,
          'order_sn'=>''
        );
      M('CouponUser')->where(array('order_id'=>$order_id,'store_id'=>$store_id))->save($data);
    }
  }

  /**
   * 礼品卡返还处理
   */
  public function refundCard($order_sn,$store_id,$refund,$payment){
    //查询此订单下是否有分单
    $count = M('StoreOrder')->where('order_sn='.$order_sn)->count();
    //查询礼品卡余额、总额
    $map = array(
        'id' => $payment['card_id']
      );
    $card_data = M('Card')->where($map)->find();
    if($refund['back_use_card'] > 0 ){
      if ($count == 1) {
        $data_card = array(
          'balance' => array('exp', 'balance + '.$payment['card_amount'])
        );
        //更新card_user表
        if ( ($card_data['balance'] + $refund['back_use_card']) == $card_data['amount'] ) {
            $data_user = array(
              'status' => 0,
              'use_time' => ''
            );
            $map_user['card_id'] = array('IN', $payment['card_id']);
            $update_card_user = M('CardUser')->where($map_user)->save($data_user);
            $data_card = array(
                'use_time' => '',
                'is_use' => 0
            );
        }
        //更新card表
        $map_card['id'] = array('IN', $payment['card_id']);
        M('Card')->where($map_card)->save($data_card);
      }else{
        //更新card表
        $data_card['balance'] = array('exp', 'balance + '.$refund['back_use_card']);
        if (($card_data['balance'] + $refund['back_use_card']) == $card_data['amount']) {
            $data_card['use_time'] = '';
            $data_card['is_use'] = 0;
        }
        $map_card['id'] = array('IN', $payment['card_id']);
        M('Card')->where($map_card)->save($data_card);
      }
    }
  }
  
  /**
   * 积分退还（下单使用积分返还、下单赠送积分返还）
   * @param  [type] $order_id [description]
   * @return [type]           [description]
   */
  public function refundScore($order_id,$order_sn,$refund){
    $res = M('ScoreLog')->where(array('order_sn'=>$order_sn))->select();
    //下单返还使用积分
      if ($refund['back_use_score'] > 0) {
        foreach ($res as $key => $value) {
          if($value['type'] == 'out' && strpos($value['memo'],'使用') != false){
            $cdata = array(
              'uid' => $value['uid'],
              'order_id' => $value['order_id'],
              'order_sn' => $value['order_sn'],
              'type' => 'in',
              'amount' => $refund['back_use_score'],
              'memo' => '购物订单退款返还使用积分',
              'create_time' => NOW_TIME,
            );
            M('ScoreLog')->add($cdata);
            M('Member')->where(array('uid' => $value['uid']))->setInc('score', $refund['back_use_score']);
          }
        }
      }
    //返还赠送积分
      if ($refund['back_send_score'] > 0) {
        //记录积分返还日志
        foreach ($res as $key => $value) {
          //下单商品赠送积分返还
          if ($value['type'] == 'in' && (strpos($value['memo'],'赠送') != false) && ($value['order_id'] == $order_id) ) {
              $data = array(
              'uid' => $value['uid'],
              'order_id' => $value['order_id'],
              'order_sn' => $value['order_sn'],
              'type' => 'out',
              'amount' => $refund['back_send_score'],
              'memo' => '购物订单退款返还赠送积分',
              'create_time' => NOW_TIME,
            );
            $map = array('order_id'=>$order_id,'type'=>'in','order_sn'=>$value['order_sn'],'memo'=>'购物订单完成赠送积分');
            M('ScoreLog')->where($map)->setField('status',1);
            M('ScoreLog')->add($data);
          }
        }
      } 
  }

  /**
   * 单笔退款 微信退款
   * @param int $refund_id 退款记录ID
   */
  public function dealRefund($refund_id){
    $return_data = array('status' => 0, 'info' => '退款出错了');
    $data = M('Refund')->find($refund_id);
    if($data['type'] ==1 ){
      $data['order'] = M('Order')->find($data['order_id']);
    }else{
      $data['order'] = M('Join_order')->find($data['order_id']);
    }
    if($data['refund_satus'] != 2){
      $return_data['info'] = '当前状态，不可进行退款操作';
      return $return_data;
    }
    //微信退款
    if($data['payment_type'] == 'wechatpay'){
      $pay_data = M('Payment')->getById($data['order']['payment_id']);
      $out_refund_no = date('YmdHis').mt_rand(100000, 999999);
      import('Org.Wechat.Pay.WxPayPubHelper', '', '.php');
      $payment_way = C('WECHATPAY');
      $refund_api = new \Refund_pub();
      $refund_api->setParameter("transaction_id", $pay_data['payment_sn']); //
      $refund_api->setParameter('out_refund_no', $out_refund_no);
      $refund_api->setParameter('total_fee', $pay_data['payment_amount']*100);
      $refund_api->setParameter('refund_fee', $data['order']['total_amount']*100);
      $refund_api->setParameter('op_user_id', $payment_way['mch_id']);
      //退款
      $res = $refund_api->getResult();
      
      if($res['return_code'] == 'FAIL'){
        $refund_query_api = new \RefundQuery_pub();
        $refund_query_api->setParameter("transaction_id", $pay_data['payment_sn']); //openid
        //退款状态
        $res_query = $refund_query_api->getResult();
      }
      if($res['return_code'] == 'SUCCESS' || $res_query['result_code'] == 'SUCCESS'){
        $save_data = array(
          'refund_no' => $out_refund_no,
          'refund_status' => 3,
          'refund_return' => json_encode($res),
        );
        M('Refund')->where(array('id' => $data['id']))->save($save_data);
        $order_id = M('Refund')->where('id='.$data['id'])->getField('order_id');
        $this->series_refund($order_id);
        return array('status' => 1, 'info' => '退款发起成功');
      }else{
        $return_data['info'] = $res['return_msg'];
      }
    }
    return $return_data;
  }

  /**
   * 查询退款时 各支付方式退款金额
   * @author buddha <[email address]>
   * @param  [type] $order_id [description]
   * @return [type]           [description]
   */
  public function getBackAmount($order_id){

      //指定模型表
      $soModel = M('StoreOrder');
      $oModel  = M('Order');
      $pModel  = M('Payment');
      $slModel = M('ScoreLog');
      $fModel  = M('Finance');
      $clModel = M('CardLog');
      $refundModel = M('Refund');
      $iModel = M('Item');

      //查询商户订单表
      $store_order = $soModel->find($order_id);
      //查询支付表
      $payment_data = $pModel->find($store_order['payment_id']);
      //查询平台订单表
      $order = $oModel->where('order_sn='.$store_order['order_sn'])->find();
      //查询商户订单支付和
      $amount = $soModel->where('order_sn='.$store_order['order_sn'])->sum('total_amount');
      //查询订单是否有分单
      $order_count = $soModel->where('order_sn='.$store_order['order_sn'])->count();
      $data = array(
            'back_use_score'   => 0,
            'back_use_finance' => 0,
            'back_use_card'    => 0,
            'back_use_online'  => 0,
            'back_send_score'  => 0,
        );
      //查询订单使用支付方式：积分、余额、礼品卡、三方
      if ($payment_data['use_score'] > 0) {
        //积分:消费积分
        $map = array(
            'type'     => 'out',
            'order_sn' => $store_order['order_sn'],
            'memo'     => '购物订单完成使用积分'
          );
        $score_data = $slModel->where($map)->find();
        if ($score_data) {
            if ($order_count > 1) {
                $data['back_use_score'] = sprintf('%.2f',$store_order['total_amount'] / $amount * $score_data['amount']);
            }else{
                $data['back_use_score'] = $score_data['amount'];
            }
        }
      }
      //赠送积分
      $where = array(
            'type'     => 'in',
            'order_sn' => $store_order['order_sn'],
            'order_id' => $order_id,
            'memo'     => '购物订单完成赠送积分'
          );
      $score_cdata = $slModel->where($where)->find();
      if ($score_cdata) {
          $data['back_send_score'] = $score_cdata['amount'];
      }
      if ($payment_data['is_use_finance'] == 1 && $payment_data['finance_amount'] > 0) {//余额
         $map1 = array(
                'type'     => 'website',
                'flow'     => 'out',
                'order_id' => $order['id']
              );
         $finance_pay_amount = $fModel->where($map1)->getField('amount');
         if($finance_pay_amount > 0){
            if ($order_count > 1) {
              $maps1 = array(
                  'type'     => 'refund',
                  'flow'     => 'in',
                  'order_id' => $order['id']
                );
              $back_finance_count =$fModel->where($maps1)->count();
              if ( ($back_finance_count + 1) == $order_count ) {
                  $back_finance =$fModel->where($maps1)->sum('amount');
                  $data['back_use_finance'] =  sprintf('%.2f',$payment_data['finance_amount'] - $back_finance);
              }else{
                  $data['back_use_finance'] = sprintf('%.2f',$store_order['total_amount']/$amount*$payment_data['finance_amount']);
              }
            }else{
              $data['back_use_finance'] = $payment_data['finance_amount'];
            }
         }
      }
      if($payment_data['is_use_card'] == 1 && $payment_data['card_id'] > 0){//礼品卡
        $map2 = array(
            'order_sn' => $store_order['order_sn'],
            'card_id'  => $payment_data['card_id']
          );
        $card_pay_amount = $clModel->where($map2)->getField('amount');
        if ($order_count > 1) {
            $data['back_use_card'] = sprintf('%.2f',$store_order['total_amount']/$amount*$payment_data['card_amount']);
        }else{
            $data['back_use_card'] = $payment_data['card_amount'];
        }
      }
      if ($payment_data['payment_amount'] > 0) {//三方
         if($order_count > 1){
            $payment_return = json_decode($payment_data['payment_return'], true);
            $trade_no = $payment_return['trade_no'];
            $trade_no = (!empty($trade_no)) ? $trade_no : ( (!empty($payment_return['transaction_id'])) ? $payment_return['transaction_id'] : $payment_data['payment_sn'] );
            $map3 = array(
                'trade_no'     => $trade_no,
                'payment_type' => $payment_data['payment_type']
              );
            $back_online_count = $refundModel->where($map3)->count();
            if($order_count == ($back_online_count + 1) ){
                $back_online_amount = $refundModel->where($map3)->sum('amount');
                $data['back_use_online'] = sprintf('%.2f',$payment_data['payment_amount'] - $back_online_amount);
            }else{
                $data['back_use_online'] = sprintf('%.2f',$store_order['total_amount'] / $amount * $payment_data['payment_amount']);
            }
         }else{
            $data['back_use_online'] = $payment_data['payment_amount'];
         }
      }
      // 再次判断
      $score_amount = $data['back_use_score'] / C('SCORE_EXCHANGE_NUMBER');
      $new_score_amount = round($score_amount);
      $cha_score_amount = $score_amount - $new_score_amount;
      $total = $new_score_amount + $data['back_use_finance'] + $data['back_use_card'] + $data['back_use_online'];
      if ($total != $store_order['total_amount']) {
          $data['back_use_card'] = sprintf('%.2f',$data['back_use_card'] + $cha_score_amount);
          $data['back_use_online'] = sprintf('%.2f',$store_order['total_amount'] - $data['back_use_finance'] - $data['back_use_card'] - $new_score_amount);
          $data['back_use_score'] = round($data['back_use_score']);
      }
      return $data;
  }

}
